﻿//using OpenPasteSpider.Localization;
using Microsoft.AspNetCore.Http;
using System;
using Volo.Abp.Application.Services;

namespace OpenPasteSpider
{
    public abstract class OpenPasteSpiderAppService : ApplicationService
    {
        protected OpenPasteSpiderAppService()
        {
            //LocalizationResource = typeof(OpenPasteSpiderResource);
            ObjectMapperContext = typeof(OpenPasteSpiderApplicationModule);
        }
    }

    public abstract class UserAppService : ApplicationService
    {
        //private readonly IHttpContextAccessor _httpContextAccessor;

        private readonly HttpContext _httpContext;

        protected UserAppService(IHttpContextAccessor httpContextAccessor)
        {
            ObjectMapperContext = typeof(OpenPasteSpiderApplicationModule);
            _httpContext = httpContextAccessor.HttpContext;
        }

        /// <summary>
        /// 获取当前登录用户
        /// </summary>
        /// <returns></returns>
        protected int ReadLoginUserId()
        {
            var token = _httpContext.Request.Headers["token"].ToString();
            if (!string.IsNullOrEmpty(token))
            {
                var strs = token.Split("_");
                int.TryParse(strs[0], out var userid);
                return userid;
            }
            return 0;
        }

        /// <summary>
        /// 获取当前登录用户的密钥 过滤器中已经校验过了，这里只需要读取
        /// </summary>
        /// <returns></returns>
        protected string ReadLoginUserToken()
        {
            var token = _httpContext.Request.Headers["token"].ToString();
            if (!string.IsNullOrEmpty(token))
            {
                return token;
            }
            return "";
        }

        /// <summary>
        /// 读取客户端IP
        /// </summary>
        /// <returns></returns>
        protected string ReadClientIP()
        {
            string result = String.Empty;
            result = _httpContext.Request.Headers["X-Forwarded-For"];
            if (String.IsNullOrEmpty(result))
            {
                result = _httpContext.Connection.RemoteIpAddress.ToString();
            }
            if (String.IsNullOrEmpty(result))
            {
                result = _httpContext.Request.Headers["REMOTE_ADDR"];
            }

            if (result != null)
            {
                if (result.Contains(","))
                {
                    result = result.Split(',')[0];
                }
                else if (result == "::1")
                {
                    result = "127.0.0.1";
                }
            }
            return result;
        }
    }
    }
